InterviewLegend

Arrays & Hashing

Alex Chen22 min readUpdated 27 real interview reports
In this lesson
  • Climb the Two Sum to 3Sum chain, and handle the duplicate skipping that decides whether 3Sum lands clean
  • Turn a nested scan into one pass with a hash map, the trick behind most of this bank
  • Build a 2D prefix sum and slide a k-by-k window, the matrix pattern that fits a camera-first company

Snap runs its coding rounds live on HackerRank, and the bar is steady: interviewers want code that compiles and runs, not a whiteboard sketch. Pseudocode does not get credit. The problems are the standard medium-centered bank you would drill for any big-tech loop, pulled from a standard question bank rather than translated into Snapchat features. There is no "count the Snaps" gimmick. The array cluster leans on the Two Sum and 3Sum family, plus a matrix flavor that suits a camera-first company.

So the target here is fluency, fast. One idea carries most of these problems: a hash map that turns "have I already seen what completes this?" from an inner loop into a constant-time lookup. Get that reflex automatic and Two Sum, the anagram buckets, even the duplicate checks collapse into a single pass. The two-pointer variants, 3Sum chief among them, run on a sister idea: sort first, then let two indices close in from the ends so you never re-scan. Both halves, plus the matrix flavor, are below.

The Snap angle
A correct brute force that compiles and runs beats an elegant sketch that does not. Speed is the most repeated read on Snap's coding bar. Interviewers grade how fast you reach a clean, executable, correct solution, then push you to optimize it. The way to win that is to state the complexity of your first idea, get a working version compiling against the examples, and only then reach for the better structure. A half-written optimal answer that never runs reads worse here than a finished quadratic one you then improve.

The hash map as memory

Two Sum is that reflex in miniature. You want two numbers that add to a target. The brute force checks every pair with two nested loops. The fix is to walk once, and at each number ask the map a single question: have I already seen target - num? If yes, you have your pair. If no, record the current number and move on. The map remembers for you. The loop runs straight through and never backtracks.

3Sum is the natural step up from Two Sum. Fix one number, and the rest is a two-sum on the remaining slice. Sorting first opens up the two-pointer version. Put a left index just past the anchor and a right index at the end, then slide them inward based on whether the running total is too small or too big. The part that separates a clean pass from a messy one is duplicate handling, since the same triplet can be reached from repeated values.

  • The reflex: Two Sum. Walk once, ask the map for the complement target minus num, store each number as you pass it. A nested loop becomes one pass. Every other problem here reuses this pattern.
  • Sort, then close in: 3Sum (and 4Sum). Fix an anchor, then two-pointer the rest of the sorted array for the pair that completes zero. Skip repeated anchors and repeated pointer values so each triplet appears once. 4Sum is the same with one more fixed index.
  • Key by signature: Group Anagrams. Two words are anagrams when their sorted letters, or their 26-letter counts, match. Bucket each word under that signature in a map. The key is the idea; the rest is collecting buckets.
  • Carry a running best: Maximum Subarray (Kadane). Keep the best sum ending here, resetting to the current value whenever the running sum goes negative. One pass, no map, O(n). The array-trick cousin of the hashing problems.

When a problem says "find a pair," "find a triplet," or "group the matches," ask one thing. What single fact, stored or sorted as you walk, lets you answer in near-constant time at each step? For Two Sum it is the numbers seen so far. For 3Sum it is the sorted order, which makes the two-pointer slide valid. Name that fact, pick the structure that holds it, and the nested loop disappears. Almost every medium in this cluster is that one decision wearing different clothes.

The Snap angle
The person grading your code is also scoring whether you are someone to work with. Snap interviewers read every round against the company values alongside the technical signal, and in a coding round the one that bites is whether you are kind under pressure. That shows up as how you take a hint, whether you narrate your thinking, and how you react when a test fails. Treat a nudge toward the optimal as a gift, not a loss. Talk through the trade-off before you rewrite, and keep the tone collaborative even under the speed pressure. Strong-but-prickly is a reported way these loops go sideways.

The matrix lean: arrays in two dimensions

Snap's camera is the product, and a camera-first company makes grid intuition worth having in your hands. Spiral Matrix, Word Search, grid DP, and the one drilled below, the maximum-sum k-by-k submatrix, are the matrix flavor worth drilling. The unifying tool is the 2D prefix sum. Precompute, for every cell, the total of the rectangle from the origin to that cell. After that, any axis-aligned rectangle sum is four array lookups.

Think about how Snap Map renders its heatmap. Public Snaps get aggregated into geographic buckets, and the map shades the dense ones brighter as you zoom. Asking for the hottest k-by-k block of those buckets is the honest, non-gimmicky version of the classic submatrix problem, and it is the practice problem below. Stop summing each window from scratch. Build the prefix table once. After that every k-by-k total is a constant-time difference of four corners.

The Snap angle
On a camera-first product, the array problem can arrive in two dimensions, so rehearse the 2D prefix sum until it is muscle memory. The boundary arithmetic is where the must-run bar bites. The extra zero row and column, and the inclusive-versus-exclusive indexing, are where a sign error hides. A window sum that is right on the interior but wrong on the first row fails the hidden tests. You lose the round on an off-by-one rather than on the idea. Getting the prefix table correct on the first compile is the execution speed Snap grades for.

Asked at Snap

Two problems, one from each half. First 3Sum, a staple Snap array medium, where the duplicate skipping is what decides a clean pass. Then the matrix problem, the hottest k-by-k cluster, an honest framing of the maximum-sum submatrix. Build each in the editor and get it running against the examples before opening the walkthrough. Say the complexity of your first idea out loud, the way the round will ask you to.

1

3Sum: Sort and Close In

MediumSignature problem
Problem
Given an integer array nums, return all unique triplets [a, b, c] such that a + b + c == 0. The three values must sit at three different indices, and the result must contain no duplicate triplets.

Return the triplets in any order, but each distinct triplet should appear exactly once. A naive triple loop is too slow for the sizes Snap tests, so aim for the sort-plus-two-pointer solution and get the duplicate skipping right.

Input: nums = [-1,0,1,2,-1,-4]

Output: [[-1,-1,2],[-1,0,1]]

The two distinct triplets summing to zero. The repeated -1 in the input does not create a duplicate triplet because the skip logic collapses them.

Input: nums = [0,1,1]

Output: []

No triplet sums to zero.

Input: nums = [0,0,0]

Output: [[0,0,0]]

A single valid triplet, reported once even though three zeros could be ordered several ways.

How this uses the pattern

Sort the array first. Fix each value as an anchor, then run a two-pointer scan over the slice to its right looking for a pair that sums to the negation of the anchor. After recording a triplet, skip past any repeated anchor, left, or right values so each triplet is emitted once.

3Sum: Sort and Close In

Loading...
Click "Run" to execute your code

Test Cases

Input: [[-1,0,1,2,-1,-4]]Expected: [[-1,-1,2],[-1,0,1]]
Input: [[0,1,1]]Expected: []
Input: [[0,0,0]]Expected: [[0,0,0]]
Input: [[-2,0,1,1,2]]Expected: [[-2,0,2],[-2,1,1]]
Input: [[]]Expected: []
Input: [[1,2,-2,-1]]Expected: []
The Snap angle
This is a staple Snap array medium, and Two Sum is the rung right below it, so be ready to articulate the bridge: fixing one number turns 3Sum into a two-sum on the rest. The duplicate skipping is where candidates lose the round, not the core loop. With the speed-and-must-run bar, get the sorted two-pointer version compiling against the examples, then add the three skip checks. Anchor, left, and right all need de-duping, and missing any one of them shows up as a repeated triplet in the hidden tests.
Take it further
The natural extension is 4Sum, and then the general kSum, which Snap can use to probe whether your structure generalizes. 4Sum fixes two indices and two-pointers the rest, O(n cubed). The clean way to write it once is a recursive kSum that peels one fixed index per level until k drops to 2, where the two-pointer base case takes over. Same sort, same de-dup discipline at every level. (Sketched in the solution.)

Now the matrix half. The hottest k-by-k cluster is the maximum-sum submatrix in honest Snap clothing: a grid of per-bucket Snap counts, the kind that sits behind the Snap Map heatmap, and you want the densest k-by-k block. The naive answer re-sums every window from scratch. The fast one builds a 2D prefix sum once, then reads each window total as a four-corner difference.

2

Hottest Cluster: Max-Sum k-by-k Submatrix

MediumCommonly asked
Problem
A grid of integers holds the number of public Snaps posted in each geographic bucket, the kind of aggregate that feeds a Snap Map heatmap. Given the grid and an integer k, return the largest total Snaps contained in any axis-aligned k by k block of buckets.

Assume k is at least 1 and no larger than either dimension of the grid. Counts can be zero, and the harder variant allows negative deltas, so do not assume the answer involves only a corner. A window-by-window re-sum is too slow on a large map, so build the totals once.

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 2

Output: 28

The bottom-right 2-by-2 block holds 5 + 6 + 8 + 9 = 28, the densest 2-by-2 cluster.

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1

Output: 9

With k = 1 each block is one bucket, so the answer is the single hottest bucket.

Input: grid = [[-1,-2],[-3,-4]], k = 2

Output: -10

Only one 2-by-2 block exists, and its total is -10. Negative values mean the maximum is not always near a corner.

How this uses the pattern

Build a prefix-sum table P where P[i][j] is the total of every cell above-and-left of (i, j), with an extra zero row and column to avoid boundary checks. Then any k-by-k window total is P[bottom][right] minus P[top][right] minus P[bottom][left] plus P[top][left]. Slide the window over every legal position and keep the maximum.

Hottest Cluster: Max-Sum k-by-k Submatrix

Loading...
Click "Run" to execute your code

Test Cases

Input: [[[1,2,3],[4,5,6],[7,8,9]], 2]Expected: 28
Input: [[[1,2,3],[4,5,6],[7,8,9]], 1]Expected: 9
Input: [[[1,1],[1,1]], 2]Expected: 4
Input: [[[2]], 1]Expected: 2
Input: [[[-1,-2],[-3,-4]], 2]Expected: -10
Input: [[[1,2,0,1],[0,3,2,1],[1,0,4,2]], 2]Expected: 9
The Snap angle
Snap's camera and map surfaces make grid problems a natural fit, and this is the honest version: the densest k-by-k tile of a heatmap, not an invented "count the streaks" puzzle. The grading bar is execution, so the 2D prefix-sum boundary arithmetic is exactly what is being tested. The extra zero row and column, and the inclusive-versus-exclusive indexing, are where the off-by-one lives. Get the table right on the first compile and the rest is a constant-time difference per window, the clean fast solution Snap rewards.
Take it further
The real-world follow-up drops the fixed size: find the maximum-sum rectangle of any dimensions, or the max rectangle no larger than a budget K. Fix the top and bottom rows, then compress the band between them into a 1D array of column sums. Now run Kadane across that band, O(rows squared times cols). The budget-capped version swaps Kadane for a prefix sum walked with an ordered set, O(rows squared times cols log cols). The instinct carries over: collapse one dimension, then solve the cheaper 1D problem. (Discussed in the solution.)
The Snap angle
Close each problem the way the round opens: name the cost, and name where it does not fall. For 3Sum that is O(n squared) after an O(n log n) sort, with constant extra space. The duplicate skips hold correctness; they do not drive the runtime. The cluster scan is linear in the grid because the prefix table makes each window four lookups, so the cost is independent of k. Saying where the work lands, and where it stays flat, sounds like an engineer who has shipped the thing. On a loop graded for speed and clean execution, that read moves the level.

Key Takeaways

  • ✓Snap pulls standard medium-centered array and hashing problems from a common medium-tier pool, with the prompts left in plain algorithm terms. Expect 3Sum as a staple. Two Sum is the rung below it, so be ready to say that fixing one value turns 3Sum into a two-sum on the rest.
  • ✓The hash map that remembers what you have seen is the reflex under most of the cluster, turning a nested scan into a single pass. For the two-pointer problems, sort first so two indices can close in from the ends. On 3Sum, the duplicate skipping at the anchor and both pointers separates a clean pass from a repeated triplet.
  • ✓Snap is camera-first, and the grid problems fit that. Rehearse the 2D prefix sum until the padded table and four-corner formula are automatic, and seed any max-over-windows scan from a real window, not zero, so negative grids stay correct.
  • ✓The Snap-specific texture is the grading, not the problems: code that compiles and runs, delivered fast, with values read in every round. Get a correct version running against the examples first, narrate the optimization as you tighten it, then take hints gracefully.
Had your Snap interview?Tell us what they asked. Reviewed before it goes in, never with your name.
Snap interview guide

Know what Snap asks before you walk in.

19 coding · 5 system design · 15 behavioral questions

Get Premium$49 a year · Cancel anytime
Or start freeNo card.

Get their questions first.

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.